﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using NHibernate;
using NHibernate.Cfg;

namespace VegetableStore.Providers
{
    public class SessionProvider
    {
        private ISession _session;
        private ISessionFactory _sessionFac;
        private bool _reuseSession;

        #region Thread-safe Singleton
        public static SessionProvider Instance
        {
            get 
            {
                return Nested.TheSingleton;
            }
        }

        private SessionProvider()
        {
            // Read the configuration
            Configuration cfg = new Configuration();
            cfg.AddAssembly("VegetableStore");
            _sessionFac = cfg.BuildSessionFactory();
            _reuseSession = false;
        }

        private class Nested
        {
            static Nested() { }
            internal static readonly SessionProvider
                TheSingleton = new SessionProvider();
        }
        #endregion

        /// <summary>
        /// Should the session be reused? If 
        /// this property is false (default), a Session-Per-Request
        /// is applied.
        /// </summary>
        public bool ReuseSession
        {
            get
            {
                return _reuseSession;
            }
            set
            {
                _reuseSession = value;
            }
        }       

        /// <summary>
        /// Get the current session. If the session is null,
        /// Open a new Session
        /// </summary>
        /// <returns>ISession-Object</returns>
        public ISession GetSession()
        {
            if (_session == null)
                _session = _sessionFac.OpenSession();
            return _session;
        }

        /// <summary>
        /// Close a Session, if the flag ReuseSession is false
        /// </summary>
        public void CloseSession()
        {
            if (_session != null)
            {
                if (!_reuseSession)
                {
                    _session.Close();
                    _session = null;
                }
            }
        }
    }
}